import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Ap0stoL2
 * Date: 2023-08-03
 * Time: 21:26
 */


//callable 类型
public class Demo27 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        //这里Integer 指定返回参数
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int sum = 0;
                for (int i = 1; i <= 1000; i++) {
                    sum += i;
                }
                return sum;
            }
        };

        // FutureTask 可以用 callable 构造, Integer为callable 的返回参数,而Thread 的构造可以接受 FutureTask
        // FutureTask 就可以帮助我们 记录callable 返回的结果
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        Thread t = new Thread(futureTask);
        t.start();
        //获取callable call方法的返回结果
        //这里的get 类似于join一样,如果callable还没算完则 会阻塞等待至 callable完成任务
        int result = futureTask.get();
        System.out.println(result);
    }
}
